package com.googlecode.imanager.swing;

import java.awt.Graphics;

import javax.swing.ImageIcon;
import javax.swing.JPanel;

import com.googlecode.imanager.client.Picture;
import com.googlecode.imanager.client.bridge.IPicture;
import com.googlecode.imanager.client.media.Image;
import com.googlecode.imanager.client.util.Utils;
import com.googlecode.imanager.core.base.BridgeApplication;
import com.googlecode.imanager.core.base.DefaultImage;

/**
 * @author wellsantos@wellsantos.com
 * @since 0.01
 */
public class SwingPicture extends SwingControl implements IPicture {

    private java.awt.Image image;
    
    public SwingPicture(BridgeApplication bridge, Picture source) {
        super(bridge, source);
    }

    @Override
    protected PictureImpl createTarget() {
        return new PictureImpl();
    }

    @Override
    public PictureImpl getTarget(){
        return (PictureImpl) target;
    }
    
    @Override
    public Picture getSource() {
        return (Picture) source;
    }

    @Override
    protected void destroy() {
        image = null;
        super.destroy();
    }

    public void setImage(Image sourceImage) {
        java.awt.Image oldImage = this.image;
        java.awt.Image newImage = null;
        
        if (sourceImage instanceof DefaultImage){
            sourceImage.loadContent();
            
            Object cache = ((DefaultImage)sourceImage).getCachedContent();
            if (cache instanceof ImageIcon){
                newImage = ((ImageIcon) cache).getImage();
            }
        }

        this.image = newImage;

        if (!Utils.isEquals(oldImage, newImage)){
            getTarget().repaint();
        }
    }
    
    
    /**
     * @author wellsantos@wellsantos.com
     * @since 0.01
     */
    protected class PictureImpl extends JPanel {

        private static final long serialVersionUID = 1L;

        @Override
        protected void paintComponent(Graphics g) {
            if (image == null
                    || image.getWidth(null) <= 0
                    || image.getHeight(null) <= 0) {
                
                g.setColor(getBackground());
                g.fillRect(0, 0, getWidth(), getHeight());
            }
            if (image != null){
                g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
            }
        }

    }
    
}
